package juc;

import org.junit.Test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author: feiwang_6
 * @create: 2020/6/29 12:03
 * @description:
 */
public class TestLock {
    
    @Test
    public void testReentrantLock() throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();
        lock.lock();
        
        lock.unlock();

        Condition condition = lock.newCondition();
        condition.await();
        
        condition.signal();
        
    }
    
    @Test
    public void testReentrantReadWriteLock(){
        ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
        ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();
        writeLock.lock();
        writeLock.unlock();

        ReentrantReadWriteLock.ReadLock readLock = lock.readLock();
        readLock.lock();
        readLock.unlock();
    }
    
    @Test
    public void countDownLatch(){
        CountDownLatch latch = new CountDownLatch(4);
        for(int j = 1; j < 4; j++){
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + "start....");
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "end....");
            }).start();
        }

        latch.countDown();
        System.out.println(latch.getCount());
        latch.countDown();
        System.out.println(latch.getCount());
        latch.countDown();
        System.out.println(latch.getCount());
        latch.countDown();
        System.out.println(latch.getCount());
        
    }
    
    @Test
    public void cyclicBarrier(){
        CyclicBarrier barrier = new CyclicBarrier(5);
        
        barrier.getParties();
    }
}
